package com.ztesoft.web.baseconfig.controller;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ztesoft.core.common.Page;
import com.ztesoft.core.idproduce.ISequenceGenerator;
import com.ztesoft.framework.exception.BaseAppException;
import com.ztesoft.framework.log.ZTEsoftLogManager;
import com.ztesoft.framework.util.Utils;
import com.ztesoft.web.baseconfig.db.dao.DmPlanDao;
import com.ztesoft.web.baseconfig.db.dao.DmPlanRelationDao;
import com.ztesoft.web.baseconfig.db.dao.DmStrategyDao;
import com.ztesoft.web.baseconfig.db.po.DmPlanPO;
import com.ztesoft.web.baseconfig.db.po.DmPlanRelationPO;
import com.ztesoft.web.baseconfig.db.po.DmSrcTablePO;
import com.ztesoft.web.baseconfig.db.po.DmStrategyPO;
import com.ztesoft.web.baseconfig.db.po.DmTargetTablePO;
import com.ztesoft.web.baseconfig.db.po.SubTableDefinePO;
import com.ztesoft.web.baseconfig.db.po.TargetColMapPO;
import com.ztesoft.web.baseconfig.service.IDmPlanService;
import com.ztesoft.web.baseconfig.service.IDmTargetTableService;
import com.ztesoft.web.baseconfig.service.ISubTableDefineService;
import com.ztesoft.web.baseconfig.service.ITargetColMapService;
import com.ztesoft.web.common.DMSConstant.Status;
import com.ztesoft.web.taskgenerator.db.arg.DmTaskArg;
import com.ztesoft.web.taskgenerator.db.dao.DmTaskDao;
import com.ztesoft.web.taskgenerator.db.dao.DmTaskStageDao;
import com.ztesoft.web.taskgenerator.db.po.DmTaskPO;
import com.ztesoft.web.taskgenerator.db.po.DmTaskStagePO;
import com.ztesoft.web.taskgenerator.service.IDmTaskService;

/**
 * <Description>计划管理 <br>
 * 
 * @author lin.jie <br>
 * @version 1.0<br>
 * @taskId <br>
 * @CreateDate 2015年8月1日 <br>
 * @since V1.0<br>
 * @see com.ztesoft.web.baseconfig.controller <br>
 */

@Controller
@RequestMapping("/baseconfig/dmplan")
public class DmPlanController {

	private static final ZTEsoftLogManager logger = ZTEsoftLogManager.getLogger(DmPlanController.class);

	@Autowired
	private IDmPlanService dmPlanService;
	@Autowired
	private DmPlanDao dmPlanDao;
	@Autowired
	private DmTaskDao dmTaskDao;
	@Autowired
	private DmTaskStageDao dmTaskStageDao;
	@Autowired
	private IDmTargetTableService dmTargetTableService;
	@Autowired
	private ISubTableDefineService subTableDefineService;
	@Autowired
	private ITargetColMapService targetColMapService;
	@Autowired
	private IDmTaskService dmTaskService;
	@Autowired
	private DmStrategyDao dmStrategyDao;
	@Autowired
	private DmPlanRelationDao dmPlanRelationDao;

	/**
	 * 主键生成器
	 */
	@Resource(name = "sequenceProcGenerator")
	private ISequenceGenerator sequenceGenerator;

	@RequestMapping("index")
	public String index(Model model) {
		return "baseconfig/jsp/dmPlan";
	}

	@RequestMapping("queryRecordByPage")
	@ResponseBody
	public Page<DmPlanPO> queryRecordByPage(DmPlanPO record, Page<DmPlanPO> resultPage) throws BaseAppException {
		resultPage = dmPlanService.selectByArgAndPage(record, resultPage);
		return resultPage;
	}

	@RequestMapping("comboboxExecType")
	@ResponseBody
	public DmPlanPO comboboxExecType() throws BaseAppException {
		// DmPlanPO record = dmPlanService.selectByExecType();
		DmPlanPO record = new DmPlanPO();
		System.out.println("=============================================");
		logger.debug("comboboxExecType record begin...record=[{0}]", record);
		return record;
	}
	
	/**
	 * 保存草稿
	 * 
	 * @param dpPO
	 * @param dttPO
	 * @param dstPO
	 * @return
	 * @throws BaseAppException
	 */
	@RequestMapping("addOfDraft")
	@ResponseBody
	public DmStrategyPO addOfDraft(DmPlanPO dpPO, DmTargetTablePO dttPO, DmSrcTablePO dstPO) throws BaseAppException, Exception {
		return dmPlanService.addOfDraft(dpPO, dttPO, dstPO);
	}
	
	/**
	 * 保存整个计划，只有一个策略
	 * 
	 * @param dpPO
	 * @param dttPO
	 * @param dstPO
	 * @return
	 * @throws BaseAppException
	 */
	@RequestMapping("addAllOneStrategy")
	@ResponseBody
	public int addAllOneStrategy(DmPlanPO dpPO, DmTargetTablePO dttPO, DmSrcTablePO dstPO) throws BaseAppException, Exception {
		return dmPlanService.addAllOneStrategy(dpPO, dttPO, dstPO);
	}

	/**
	 * 草稿箱查询
	 * 
	 * @param record
	 * @param resultPage
	 * @return
	 * @throws BaseAppException
	 */
	@RequestMapping("queryRecordByPageDraft")
	@ResponseBody
	public Page<DmPlanPO> queryRecordByPageDraft(DmPlanPO record, Page<DmPlanPO> resultPage) throws BaseAppException {
		resultPage = dmPlanService.selectByArgAndPageDraft(record, resultPage);
		return resultPage;
	}

	/**
	 * 计划维护查询
	 * 
	 * @param record
	 * @param resultPage
	 * @return
	 * @throws BaseAppException
	 */
	@RequestMapping("queryRecordByPageMaint")
	@ResponseBody
	public Page<DmPlanPO> queryRecordByPageMaint(DmPlanPO record, Page<DmPlanPO> resultPage) throws BaseAppException {
		resultPage = dmPlanService.selectByArgAndPageMaint(record, resultPage);
		return resultPage;
	}

	/**
	 * 保存到草稿箱：保证计划名称不同 1、用户新增计划的中途，保存草稿 2、草稿箱列表，编辑
	 * 
	 * @param record
	 * @return record.dmPlanId=0：存在相同名称的计划，不可以保存草稿
	 * @throws Exception
	 */
	@RequestMapping("addForDraft")
	@ResponseBody
	public DmPlanPO addForDraft(DmPlanPO record) throws Exception {
		logger.debug("addForDraft record begin...record=[{0}]", record);
		// 通过前台传回来的ID，从数据库里找，是否已经有这条数据了
		DmPlanPO dpPO = dmPlanDao.selectByPrimaryKey(record.getDmPlanId());
		if (Utils.notEmpty(dpPO)) {
			record.setState(dpPO.getState());
		}
		if (record.getDmPlanId() == 0) {
			record.setDmPlanId(sequenceGenerator.sequenceIntValue("DM_PLAN", "DM_PLAN_ID"));
		}
		return dmPlanService.add(record);
	}

	/**
	 * 
	 * @param record
	 * @return record.dmPlanId=0：存在相同名称的计划，不可以保存草稿
	 *         record.dmPlanId=-1：该计划下的任务已经执行了，不能修改
	 * @throws BaseAppException
	 */
	@RequestMapping("add")
	@ResponseBody
	public DmPlanPO add(DmPlanPO record) throws BaseAppException, Exception {
		logger.debug("添加计划信息，计划信息=[{0}]", record);
		// 先查看该计划下有没有在执行的任务
		// 查看任务结果明细表和任务结果明细历史表，看是否有该任务ID的记录，若有，则说明该任务执行过
		DmTaskPO dtPO = new DmTaskPO();
		dtPO = dmTaskDao.getOneBydmPlanId(record.getDmPlanId());
		if (Utils.notEmpty(dtPO)) {
			if (Utils.notEmpty(dtPO.getParentTaskId())) {// 有父任务，说明是子任务，说明任务已经执行，不能修改计划
				record.setDmPlanId(-1);
				return record;
			}
			// 判断任务是不是已经完成
			if (!dtPO.getState().equals(Status.SUCCESS.toString())) {
				List<DmTaskStagePO> dtsPOList = dmTaskStageDao.getCheckObjNameByTaskId(dtPO.getDmTaskId());
				for (DmTaskStagePO dtsPO : dtsPOList) {
					// 先判断结果明细表是否生成，没生成则说明任务没有执行
					dtPO.setDmTableName("dm_" + dtsPO.getCheckObjName());
					// dtPO.setDmTableName("dm_" + "plan");
					DmTaskPO dtPO_count = new DmTaskPO();
					dtPO_count = dmTaskDao.hasCreated(dtPO);
					if (Utils.notEmpty(dtPO_count) && Utils.notEmpty(dtPO_count.getTableName())) {// 任务结果明细表已经生成
						dtPO_count = dmTaskDao.isStarted(dtPO);
						if (dtPO_count.getCount() != 0) {
							// 有该任务的任务结果明细表中有该任务的信息，说明任务已经执行了
							record.setDmPlanId(-1);
							return record;
						}
					}
					// 再判断结果明细历史表中有没有该任务的信息
					dtPO.setDmTableName("dm_" + dtsPO.getCheckObjName() + "_his");
					DmTaskPO dtPO_count_his = new DmTaskPO();
					dtPO_count_his = dmTaskDao.hasCreated(dtPO);
					if (Utils.notEmpty(dtPO_count_his) && Utils.notEmpty(dtPO_count_his.getTableName())) {// 任务结果明细历史表已经生成
						dtPO_count_his = dmTaskDao.isStarted(dtPO);
						if (dtPO_count_his.getCount() != 0) {
							// 有该任务的任务结果明细历史表中有该任务的信息，说明任务已经执行了
							record.setDmPlanId(-1);
							return record;
						}
					}
				}
			}
		}

		// 这个要放到后面一步。。。。。。。。。。。。。。。。。。。
		if (record.getOperType() == 0 && record.getIsEdit() == 1) {// 修改状态下并且操作类型为-体检备份清理，对该计划下的所有策略的目标表进行校验
			List<DmPlanPO> sourcePOList = dmPlanService.selectSourceByDmPlanId(record.getDmPlanId());
			int dtt = 0;
			if (sourcePOList.size() != 0) {
				for (DmPlanPO sourcePO : sourcePOList) {
					DmTargetTablePO dttPO = dmTargetTableService.selectBySourceId(sourcePO.getSourceDataId());
					if (Utils.notEmpty(dttPO)) {
						dtt = dtt + 1;
					}
				}
				if (sourcePOList.size() > 1 && (sourcePOList.size() - dtt) > 1) {
					record.setDmPlanId(-9);// 隐藏完成提交按钮，提示点击继续添加策略按钮
					return record;
				}
			}
		}

		// 判断计划下是否还有草稿箱状态的策略（00D）
		List<DmPlanRelationPO> dprPOList = dmPlanRelationDao.selectByDmPlanId00X(record.getDmPlanId());
		for (DmPlanRelationPO dprPO : dprPOList) {
			DmStrategyPO dsPO = dmStrategyDao.selectByPrimaryKey(dprPO.getDmStrategyId());
			if (!record.getDmStrategyId().equals(dsPO.getDmStrategyId())) {
				if ((Status.DRAFT.toString()).equals(dsPO.getState())) {
					record.setDmPlanId(-9);
					return record;
				}
			}
		}
		
		if (record.getOperType() == 1 || record.getOperType() == 2) {// 不需要备份，把改计划下的所有目标表以及其他相关表都干掉
			if (Utils.notEmpty(record.getDmPlanId())) {
				// 找出改计划下的所有目标表
				List<DmTargetTablePO> dttPOList = dmTargetTableService.selectByDmPlanId(record.getDmPlanId());
				if (dttPOList.size() != 0) {
					// 把目标表以及其他相关表都干掉
					for (DmTargetTablePO dttPO : dttPOList) {
						// 目标表
						dttPO.setStaffId(record.getStaffId());
						dmTargetTableService.delete(dttPO);
						// 分表定义
						SubTableDefinePO stdPO = new SubTableDefinePO();
						stdPO.setSourceDataId(dttPO.getTargetDataId());
						stdPO.setStaffId(record.getStaffId());
						subTableDefineService.delete(stdPO);
						// 目标字段映射
						TargetColMapPO tcmPO = new TargetColMapPO();
						tcmPO.setTargetDataId(dttPO.getTargetDataId());
						targetColMapService.delete(tcmPO);
					}
				}
			}
		}
		record.setState(Status.SUCCESS.toString());
		return dmPlanService.add(record);
	}

	@RequestMapping("addAllStrategy")
	@ResponseBody
	public int addAllStrategy(DmPlanPO record) throws BaseAppException, Exception {
		return dmPlanService.addAllStrategy(record);
	}

	@RequestMapping("addOne")
	@ResponseBody
	public DmPlanPO addOne(DmPlanPO record) throws BaseAppException, Exception {
		logger.debug("添加计划信息，计划信息=[{0}]", record);
		// 先查看该计划下有没有在执行的任务
		// 查看任务结果明细表和任务结果明细历史表，看是否有该任务ID的记录，若有，则说明该任务执行过
		DmTaskPO dtPO = dmTaskDao.getOneBydmPlanId(record.getDmPlanId());
		if (Utils.notEmpty(dtPO.getParentTaskId())) {// 有父任务，说明是子任务，说明任务已经执行，不能修改计划
			record.setDmPlanId(-1);
			return record;
		}
		// 判断任务是不是已经完成
		if (!dtPO.getState().equals(Status.SUCCESS.toString())) {
			List<DmTaskStagePO> dtsPOList = dmTaskStageDao.getCheckObjNameByTaskId(dtPO.getDmTaskId());
			for (DmTaskStagePO dtsPO : dtsPOList) {
				dtPO.setDmTableName("dm_" + dtsPO.getCheckObjName());
				DmTaskPO dtPO_count = dmTaskDao.isStarted(dtPO);
				dtPO.setDmTableName("dm_" + dtsPO.getCheckObjName() + "_his");
				DmTaskPO dtPO_count_his = dmTaskDao.isStarted(dtPO);
				if (dtPO_count.getCount() != 0 || dtPO_count_his.getCount() != 0) {
					// 两个表（dm_*、dm_*_his）其中至少有一个表里有该任务的任务结果明细信息，说明任务已经执行了
					record.setDmPlanId(-1);
					return record;
				}
			}
		}

		// 这个要放到后面一步。。。。。。。。。。。。。。。。。。。
		if (record.getOperType() == 0 && record.getIsEdit() == 1) {// 修改状态下并且操作类型为-体检备份清理，对该计划下的所有策略的目标表进行校验
			List<DmPlanPO> sourcePOList = dmPlanService.selectSourceByDmPlanId(record.getDmPlanId());
			if (sourcePOList.size() != 0) {
				for (DmPlanPO sourcePO : sourcePOList) {
					DmTargetTablePO dttPO = dmTargetTableService.selectBySourceId(sourcePO.getSourceDataId());
					if (Utils.isEmpty(dttPO)) {
						record.setDmPlanId(-9);
						return record;
					}
				}
			}
		}
		if (record.getOperType() == 1 || record.getOperType() == 2) {// 不需要备份，把改计划下的所有目标表以及其他相关表都干掉
			if (Utils.notEmpty(record.getDmPlanId())) {
				// 找出改计划下的所有目标表
				List<DmTargetTablePO> dttPOList = dmTargetTableService.selectByDmPlanId(record.getDmPlanId());
				if (dttPOList.size() != 0) {
					// 把目标表以及其他相关表都干掉
					for (DmTargetTablePO dttPO : dttPOList) {
						// 目标表
						dttPO.setStaffId(record.getStaffId());
						dmTargetTableService.delete(dttPO);
						// 分表定义
						SubTableDefinePO stdPO = new SubTableDefinePO();
						stdPO.setSourceDataId(dttPO.getTargetDataId());
						stdPO.setStaffId(record.getStaffId());
						subTableDefineService.delete(stdPO);
						// 目标字段映射
						TargetColMapPO tcmPO = new TargetColMapPO();
						tcmPO.setTargetDataId(dttPO.getTargetDataId());
						targetColMapService.delete(tcmPO);
					}
				}
			}
		}
		record.setState(Status.SUCCESS.toString());
		return dmPlanService.add(record);
	}

	@RequestMapping("updateDToA")
	@ResponseBody
	public DmPlanPO updateDToA(@RequestParam(value = "dmPlanId", required = true) Integer dmPlanId)
			throws BaseAppException {
		return dmPlanService.updateDToA(dmPlanId);
	}

	@RequestMapping("update")
	@ResponseBody
	public DmPlanPO update(DmPlanPO record) throws BaseAppException {
		logger.debug("modify record begin...record=[{0}]", record);
		dmPlanService.update(record);
		return record;
	}

	@RequestMapping("upexpDate")
	@ResponseBody
	public DmPlanPO upexpDate(DmPlanPO record) throws BaseAppException {
		logger.debug("modify record begin...record=[{0}]", record);
		dmPlanService.upexpDate(record);
		return record;
	}

	/**
	 * 失效时间修改
	 * 
	 * @param dmPlanId
	 * @return
	 * @throws BaseAppException
	 */
	@RequestMapping("changeTime")
	@ResponseBody
	public DmPlanPO changeTime(Integer dmPlanId) throws BaseAppException {
		logger.debug("delete record begin...record=[{0}]", dmPlanId);
		return dmTaskService.changeTime(dmPlanId);
	}

	/**
	 * 除非有“待执行且已处理了部分数据”或执行中或失败的任务，否则计划是可以进行修改的
	 * 
	 * @param dmPlanId
	 * @return success：true 可以修改 false：不能修改 info：相关提示信息
	 * @throws BaseAppException
	 */
	@RequestMapping("hasRunningTask")
	@ResponseBody
	public Map<String, Object> hasRunningTask(@RequestParam(value = "dmPlanId", required = true) Integer dmPlanId)
			throws BaseAppException {
		logger.debug("判断计划下是否有正在执行的任务，计划ID=[{0}]", dmPlanId);
		return dmTaskService.hasRunningTask(dmPlanId);
	}

	// 删除草稿箱，把状态改为00X
	@RequestMapping("delete")
	@ResponseBody
	public int delete(Integer dmPlanId) throws BaseAppException {
		logger.debug("delete record begin...record=[{0}]", dmPlanId);
		return dmPlanService.delete(dmPlanId);
	}

	// 删除计划维护，把状态改为00X
	@RequestMapping("deleteMaint")
	@ResponseBody
	public int deleteMaint(Integer dmPlanId) throws BaseAppException {
		logger.debug("delete record begin...record=[{0}]", dmPlanId);
		return dmPlanService.deleteMaint(dmPlanId);
	}

	// 删除计划维护，把状态改为00X-00T
	@RequestMapping("deleteMaint00T")
	@ResponseBody
	public int deleteMaint00T(Integer dmPlanId) throws BaseAppException {
		logger.debug("delete record begin...record=[{0}]", dmPlanId);
		return dmPlanService.deleteMaint00T(dmPlanId);
	}

	@RequestMapping("qryRecordInfo")
	@ResponseBody
	public DmPlanPO qryRecordInfo(@RequestParam(value = "dmPlanId", required = true) Integer dmPlanId)
			throws BaseAppException {
		DmPlanPO record = dmPlanService.selectByPrimaryKey(dmPlanId);
		logger.debug("qryRecordInfo record begin...record=[{0}]", record);
		return record;
	}

}
